<template>
  <div>Axios的使用</div>
  <div>
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>name</th>
          <th>age</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data.list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <th>
            <button @click="getInfo(item.id)">详情</button>
            <!-- 绑定更新弹窗方法 -->
            <button @click="openUpdateDialog(item)">更新</button>
            <button @click="deleteUserById(item.id)">删除</button>
          </th>
        </tr>
      </tbody>
    </table>

    <button @click="dialogVisible.show = true" style="margin-top: 20px;">新增</button>

    <!-- 新增弹窗 -->
    <div v-if="dialogVisible.show" style="border: 1px solid #ccc; padding: 20px; width: 240px; margin-top: 20px;">
      <input v-model="form.name" placeholder="请输入姓名" style="display: block; margin-bottom: 10px;">
      <input v-model.number="form.age" placeholder="请输入年龄" type="number" style="display: block; margin-bottom: 10px;">
      <button @click="handleAdd">提交</button>
      <button @click="dialogVisible.show = false">取消</button>
    </div>

    <!-- 更新弹窗 -->
    <div v-if="updateDialog.show" style="border: 1px solid #ccc; padding: 20px; width: 240px; margin-top: 20px;">
      <input v-model="updateDialog.form.name" placeholder="请输入姓名" style="display: block; margin-bottom: 10px;">
      <input v-model.number="updateDialog.form.age" placeholder="请输入年龄" type="number" style="display: block; margin-bottom: 10px;">
      <button @click="submitUpdate">提交更新</button>
      <button @click="updateDialog.show = false">取消</button>
    </div>
  </div>
</template>

<script setup>
import axios from "axios"
import { reactive } from "vue"

const data = reactive({
  list: []
})

const form = reactive({
  name: "",
  age: ""
})

const dialogVisible = reactive({
  show: false
})

// 新增：更新功能的响应式数据和方法
const updateDialog = reactive({
  show: false,
  form: { id: null, name: "", age: "" }
})

// 打开更新弹窗
function openUpdateDialog(item) {
  updateDialog.form = { ...item }
  updateDialog.show = true
}

// 提交更新请求
function submitUpdate() {
  axios.put("http://localhost:9123/update", updateDialog.form)
    .then(() => {
      return axios.get("http://localhost:9123/selectAll")
    })
    .then(res => {
      data.list = res.data
      updateDialog.show = false
    })
    .catch(error => {
      console.error("更新失败：", error)
    })
}

// 初始化列表数据
axios.get("http://localhost:9123/selectAll").then(response => {
  data.list = response.data
})


//这种方式自己写上当作笔记了
//也可以用这种封装方式
async function getAll() {
  try {
    const res = await axios.request({
	  url: "/user?xxx=123",	
      // url: "http://localhost:9123/selectAll?xxx=123",
      method: "get",
      headers: {
		  token: "dushaocong"
	  },
	  params:{
		  name:"dushaocong",
		  age : "18"
	  }	  
	});
    data.list = res.data;
    
  } catch (error) {
    console.error("获取列表失败：", error);
  }
}


/*
// 用 .then 实现（传统异步逻辑）
function getAll() {
  axios.request({ url: "/selectAll", method: "get" })
    .then(res => {
      data.list = res.data; // 响应回来后再赋值
    })
    .catch(error => {
      console.error("请求失败", error);
    });
}

// 用 async/await 实现（语法糖，逻辑完全等价）
async function getAll() {
  try {
    const res = await axios.request({ url: "/selectAll", method: "get" });
    data.list = res.data;
  } catch (error) {
    console.error("请求失败", error);
  }
}
*/


// 新增数据逻辑
function handleAdd() {
  axios.post("http://localhost:9123/save", form).then(response => {
    if (response.data) {
      axios.get("http://localhost:9123/selectAll").then(res => {
        data.list = res.data
      })
      form.name = ""
      form.age = ""
      dialogVisible.show = false
    }
  })
}

// 查看详情
function getInfo(id) {
  axios.get(`http://localhost:9123/getUserById/${id}`)
    .then(res => {
      console.log("用户详情响应：", res.data)
    })
    .catch(error => {
      console.error("获取详情失败：", error)
    })
}

// 删除数据
function deleteUserById(id) {
  axios.delete(`http://localhost:9123/delete/${id}`)
    .then(() => {
      return axios.get("http://localhost:9123/selectAll")
    })
    .then(res => {
      data.list = res.data
    })
}






//下面是axios实例的方式
/*
const blogAxios=axios.create({
	baseURL:"http://localhost:9123",
	timeout:1000,
})

async function getBlogList(){
	let res = await blogAxios.get("/users")
    console.log("bo ke hou duan ",res.data)
}


//调用
getBlogList()
*/























</script>

<style scoped>
</style>